package com.waikuai.shop.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Web MVC配置类
 * @author waikuai
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final Path photoDir;

    public WebConfig(@Value("${business.upload.path:/uploads}") String uploadRoot) {
        Path baseDir = Paths.get(uploadRoot).toAbsolutePath().normalize();
        this.photoDir = baseDir.resolve("photo");
        try {
            Files.createDirectories(this.photoDir);
        } catch (IOException e) {
            throw new IllegalStateException("无法创建商品图片目录：" + this.photoDir, e);
        }
    }

    /**
     * 配置跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .maxAge(3600);
    }

    /**
     * 配置静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置头像文件访问路径（实际访问地址为 /api/avatars/**，需要去掉context-path）
        registry.addResourceHandler("/avatars/**")
                .addResourceLocations("classpath:/static/avatars/");

        // 配置商品图片文件访问路径
        registry.addResourceHandler("/photo/**")
                .addResourceLocations(withTrailingSlash(photoDir));
    }

    private static String withTrailingSlash(Path path) {
        String uri = path.toUri().toString();
        return uri.endsWith("/") ? uri : uri + "/";
    }
}